package validation;

import java.io.*;
import java.lang.String;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;

import javax.sound.sampled.*;


public class VSoundGenerator {
	private static final String relURL="c:\\voices\\";
	private static final String codePostfix=".wav";
	private static final String noiseRelURL="c:\\voices\\noises\\";
	private static final String noisePostfix=".wav";
	private static final int noiseNr=10;
	private static final boolean useNoise=true;
	private static final int secondsSilence=1;
	//private static final float backgroundAmplitude=(float)0.1;
	
	public static ByteArrayOutputStream getSound(String code){
		int size=code.length();
		AudioFormat finalFormat=null;
		List audioList=new ArrayList();
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		try{
			for(int i=0;i < size;i++){
				File f=new File(relURL+code.charAt(i)+codePostfix);
					AudioInputStream stream=AudioSystem.getAudioInputStream(f);
				
					AudioFormat format=stream.getFormat();
					if(finalFormat == null)
						finalFormat=format;
					else if(!finalFormat.matches(format))
						return null;
					audioList.add(new SilenceAudioInputStream(stream.getFormat(),secondsSilence*1000));
					audioList.add(stream);	
			}
			
			AudioInputStream in= new SequenceAudioInputStream(finalFormat,audioList);
			if(useNoise){
				File noise=new File(noiseRelURL+"n"+(new Random().nextInt(noiseNr)+1)+noisePostfix);
				AudioInputStream stream=AudioSystem.getAudioInputStream(noise);
				ArrayList mixArr=new ArrayList();
				
				if(!stream.getFormat().matches(finalFormat))
					in=AudioSystem.getAudioInputStream(in.getFormat(),in);
				
				mixArr.add(in);
				mixArr.add(stream);
				
				AudioInputStream mixer=new MixingAudioInputStream(finalFormat,mixArr);
				in=mixer;
			}
			
			AudioSystem.write(in, AudioFileFormat.Type.WAVE, out);
			
			return out;
		}catch(Exception e){e.printStackTrace();return null;}
	}
}
